#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/syslog.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

int init_daemon(const char *pname, int facility)
{
    int pid;
    int i;

    // ignore possible terminal signal.
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTSTP, SIG_IGN);
    signal(SIGHUP, SIG_IGN);

    // create child process, exit parent process.
    if ((pid=fork()))
        exit(EXIT_SUCCESS); // exit parent process
    else if (pid<0)
    {
        perror("fork error!\n");
        exit(EXIT_FAILURE);
    }

    setsid();   // set new group session , leave terminal

    for (i=0; i<256; i++)
        close(i);

    open("/dev/null", O_RDONLY);
    open("/dev/null", O_RDWR);
    open("/dev/null", O_RDWR);

    chdir("/");

    umask(0);

    signal(SIGCHLD, SIG_IGN);

    openlog(pname, LOG_PID, facility);

    return 0;
}

int main(int argc, char *argv[])
{
    time_t ticks;
    init_daemon(argv[0], LOG_KERN);
    while (1)
    {
        sleep(60);
        ticks = time(NULL);
        syslog(LOG_INFO, "%s", asctime(localtime(&ticks)));
    }
}

// cmd: tail -n 1 /var/log/message
